package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.common.pojo.User;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.common.service.PicUploadService;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.common.vo.PicUploadResult;
import com.tanhua.dubbo.server.api.QuanZiApi;
import com.tanhua.dubbo.server.api.VideoApi;
import com.tanhua.dubbo.server.pojo.Video;
import com.tanhua.dubbo.server.vo.PageInfo;
import com.tanhua.server.vo.PageResult;
import com.tanhua.server.vo.VideoVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Auther: you
 * @Date: 2021/06/01/23:22
 * @Description:
 */
@Slf4j
@Service
public class VideoService {
    @Reference(version = "1.0.0")
    private VideoApi videoApi;
    @Reference(version = "1.0.0")
    private QuanZiApi quanZiApi;
    @Autowired
    private PicUploadService picUploadService;
    @Autowired
    protected FastFileStorageClient storageClient;
    @Autowired
    private FdfsWebServer fdfsWebServer;
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private QuanZiService quanZiService;

    public Boolean saveVideo(MultipartFile picFile, MultipartFile videoFile) throws IOException {
        try {
            //视频和视频封面图像没有上传，上传失败
            if (ObjectUtil.isAllEmpty(picFile, videoFile)) {
                return false;
            }

            //视频封面图像上传阿里云，获取图像路径
            PicUploadResult picUploadResult = picUploadService.upload(picFile);
            String picUrlPath = picUploadResult.getName();

            //通过fastDFS（分布式文件系统）上传视频到其storage（存储服务器）中
            //上传视频
            StorePath storePath = storageClient.uploadFile(videoFile.getInputStream(),
                    videoFile.getSize(),
                    StrUtil.subAfter(videoFile.getOriginalFilename(), '.', true),
                    null);
            //视频url访问路径
            String videoUrlPath = fdfsWebServer.getWebServerUrl() + storePath.getFullPath();

            System.out.println(picUrlPath);
            System.out.println(videoUrlPath);

            //token校验，获取userId
            User user = UserThreadLocal.get();
            //填充video
            Video video = Video.builder().userId(user.getId()).picUrl(picUrlPath).videoUrl(videoUrlPath).build();
            video.setSeeType(1); //默认公开
            String videoId= videoApi.saveVideo(video);
            return StringUtils.isNotEmpty(videoId);
        } catch (IOException e) {
            log.error("小视频发布失败~~");
        }
        return false;
    }

    public PageResult queryVideoList(Integer pageNum, Integer pageSize) {
        User user = UserThreadLocal.get();

        PageResult pageResult = new PageResult();
        pageResult.setPage(pageNum);
        pageResult.setPagesize(pageSize);


        PageInfo<Video> videoPageInfo = videoApi.queryVideoList(user.getId(), pageNum, pageSize);
        List<Video> records = videoPageInfo.getRecords();
        if (CollUtil.isEmpty(records)){
            return pageResult;
        }

        List<Object> userIds = CollUtil.getFieldValues(records, "userId");
        List<UserInfo> userInfos = userInfoService.queryUserInfoByUserIdList(userIds);

        List<VideoVo> videoVos=new ArrayList<>();
        for (Video record : records) {
            //填充video信息
            VideoVo videoVo = new VideoVo();
            videoVo.setUserId(record.getUserId());
            videoVo.setId(Convert.toStr(record.getId()));
            videoVo.setVideoUrl(record.getVideoUrl());
            videoVo.setCover(record.getPicUrl());
            videoVo.setSignature("熊弟们，小礼物走一波~~");//TODO 签名

            videoVo.setCommentCount(Convert.toInt(quanZiApi.queryCommentCount(Convert.toStr(record.getId())))); //TODO 评论数
            videoVo.setHasFocus(videoApi.isFollowUser(user.getId(),Convert.toLong(record.getUserId())) ? 1 : 0); //TODO 是否关注
            videoVo.setHasLiked(quanZiApi.queryUserIsLike(record.getUserId(),Convert.toStr(record.getId())) ? 1 : 0); //TODO 是否点赞（1是，0否）
            videoVo.setLikeCount(Convert.toInt(quanZiApi.queryLikeCount(Convert.toStr(record.getId()))));//TODO 点赞数

            //填充用户信息
            for (UserInfo userInfo : userInfos) {
                if (ObjectUtil.equal(userInfo.getUserId(), videoVo.getUserId())) {
                    videoVo.setAvatar(userInfo.getLogo());
                    videoVo.setNickname(userInfo.getNickName());
                    break;
                }
            }
            videoVos.add(videoVo);
        }

        pageResult.setItems(videoVos);
        return pageResult;
    }

    //点赞视频
    public Long likeVedio(String videoId) {

        return quanZiService.likeComment(videoId);

    }

    //取消点赞视频
    public Long disLikeVedio(String videoId) {

        return quanZiService.disLikeComment(videoId);
    }


    //查询小视频评论列表
    public PageResult queryCommentList(String videoId, Integer page, Integer pageSize) {

        return quanZiService.queryCommentList(videoId,page,pageSize);

    }

    //对小视频发表评论
    public Boolean saveComment(String videoId, String content) {
        return quanZiService.saveComments(videoId,content);
    }


    //小视频评论点赞
    public Long likeComment(String videoCommentId) {
        return quanZiService.likeComment(videoCommentId);

    }

    //小视频评论取消点赞
    public Long disLikeComment(String videoCommentId) {
        return quanZiService.disLikeComment(videoCommentId);
    }


    //关注用户
    public Boolean followUser(Long userId) {
        User user = UserThreadLocal.get();
        return this.videoApi.followUser(user.getId(), userId);
    }

    //撤销关注
    public Boolean disFollowUser(Long userId) {
        User user = UserThreadLocal.get();
        return this.videoApi.disFollowUser(user.getId(), userId);
    }
}
